import CPostItem from "@components/post-item";
import DBScrollView from "@components/scroll-view";
import { useAppDispatch, useAppSelector } from "@src/store";
import { getPostList } from "@src/store/postList";
import {  Swiper, SwiperItem, Text, View } from "@tarojs/components";
import React, { useState ,useEffect,Fragment,useCallback ,useMemo } from "react";
import  "./index.scss";

type Props = {
}


const PostList = (props:Props)=>{
    const disPatch = useAppDispatch();
    const { postList } = useAppSelector(state=>state);


    useEffect(()=>{
      const promise =  disPatch(getPostList({ }));
      return ()=>{
        promise.abort();
      };
    },[disPatch]);

    const [current,setCurrent] = useState(0);

    const [refreshing,setRefreshing] = useState(false);
    

    const handleItemsChanged = useCallback((event)=>{
      // setCurrent(event.detail.current);
      console.log(event);
    },[]);


    useEffect(()=>{
      if(current >= postList.data.length - 1){
        const promise = disPatch(getPostList({}));

        return ()=>{
          promise.abort();
        };
      }


    },[current,postList.data.length,disPatch]);


    return (
      // <Swiper vertical  className="postList" current={current} onChange={handleItemsChanged} displayMultipleItems={2}>
      //   {
      //     postList.data.map((item,index)=><SwiperItem key={item.id}>
      //       <CPostItem data={item}  key={`${item.id}_${index}`} allShow={current == index}  />
      //     </SwiperItem>)
      //   }
<DBScrollView 
  style={{ height:"100%",width:"100%" }}
  data={postList.data} 
  // onViewableItemsChanged={handleItemsChanged}
  viewabilityConfig={{
        viewAreaCoveragePercentThreshold:50
      }}
  renderItem={({ item,index })=><CPostItem data={item}  key={`${item.id}_${index}`}   />}
  ItemSeparatorComponent={()=><View  className="scrollView__separator" />}
  ListFooterComponent={()=><Text className="scrollView__loading--bottom">{
        postList.pageNumber * postList.pageSize >= postList.total ? "我是有底线的" : "加载中。。。"
      }</Text>}
  ListEmptyComponent={()=><Fragment>
        {!postList.loading && !postList.data.length ? <View className="scrollView__emptyTips">小鹿正在努力产出内容，敬请期待</View> : <View className="scrollView__loading">Loading...</View>}
      </Fragment>}
  refreshing={refreshing}
  horizontal={false}
  showsVerticalScrollIndicator={false}
  onRefresh={(...args)=>{
          setRefreshing(true);
          setTimeout(async ()=>{
            await disPatch(getPostList({ refresh:true }));
            setRefreshing(false);
            },3000);
      }}
  onEndReached={()=>{
        // 加载更多
        console.log("到底部了");
        // disPatch(getPostList({}));
      }}
/>
    
    );
};

export default React.memo(PostList);